<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽会员/教练上课概览</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body style="background-color: rgb(254, 254, 255);">
    {% include 'show_ins_info.html' %}
    <hr>
    <h2>会员 / 教练 上课概览</h2>
    <div id="yearMonth" style="font-size:18px;margin-left:10px;"></div>
    <hr>

    
    <div id="cusClsRankBox" style="margin-top:30px;">
        <div style="font-size:16px;color:#a479b8;font-weight: bold;margin-left:10px;">■ 会员上课次数排名</div>
        <div class="form-row" style="font-size:14px;">
            <h4 style="margin-right:2px;padding-right:2px;width:60px;">时间段：</h4>
            <select id="interval0" onchange="showCusClsRank0();">
                <option value="30">近30天</option>
                <option value="60">近60天</option>
                <option value="90">近90天</option>
            </select>
        </div>   
        <div id="cusClsRank"></div>
    </div>

    <hr style="border: dashed 1px #a479b8;">
    <div id="cusTrainInfo"></div>
    
    <hr style="border: dashed 1px #3b6ba1;">

    <div style="font-size:16px;color:#bd8333;font-weight: bold;margin-left:10px;margin-top:30px;">■ 教练上课分时段统计</div>
    <div class="form-row" style="font-size:14px;display: flex;flex-direction: row;">       
        
        <div class="form-row" style="font-size:14px;">
            <h4 style="margin-right:2px;padding-right:2px;width:60px;">时间段：</h4>
            <select id="interval" onchange="showInsClsChart2();">
                <option value="30">近30天</option>
                <option value="60">近60天</option>
                <option value="90">近90天</option>
                <option value="all">全部</option>
            </select>
        </div>
    </div>    

    <div id="insClsInfo" class="chart-wrapper-ins" style="width:100%;height:200px;margin-top:20px;"></div>

    <script src="../static/js/common.js"></script>
    <script src="../static/js/echarts.min.js"></script>
    
    <script>
        let insName;
        let insId;
        let insRole;
        let insList;
        
        document.addEventListener('DOMContentLoaded',function(){
            // loginCheck();           
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insId=insInfo.sessionInsId;
            insName=insInfo.sessionInsName;
            insRole=insInfo.sessionInsRole;
            if(insRole==='ins'){
                window.location.replace('./index');
            }

            const fetch1 = fetch('/get_ins_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const dateInput = new Date();
            const today = dateToString(dateInput, 'date');
            const interval=document.getElementById('interval').value;
            const fetch2 = fetch('./get_ins_cls_info', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 'dateInput': today,'interval':interval })
            });

            const fetch3 = fetch('./get_all_cls_info', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 'dateInput': today,'interval':interval })
            });



            Promise.all([fetch1, fetch2,fetch3])
            .then(responses => Promise.all(responses.map(response => response.json())))
            .then(data => {                
                insList = data[0]['ins_list'];
                const insClsRecs = data[1]['data'];
                const allCusClsStat=data[2]['data'];

                // console.log(allCusClsStat);
                if(allCusClsStat){
                    showCusClsRank(allCusClsStat);
                }

                // const splitLine=document.getElementById('splitLine');
                const ym=document.getElementById('yearMonth');
                if(insList && insClsRecs){                    
                    const today=new Date();
                    ym.innerHTML=`${today.getFullYear()}年${today.getMonth()+1}月${today.getDate()}日`;
                    // splitLine.style.display='block';
                    // splitLine.style.borderTop='2px dashed rgb(237, 42, 42)';
                    // splitLine.style.marginBottom='10px';


                }else{
                    ym.innerHTML='';
                    // splitLine.style.display='none';
                }

                const sortInsList=insList.sort((a, b) => {
                    const aPrefix = a.substr(0, 8); // 获取a的前8位
                    const bPrefix = b.substr(0, 8); // 获取b的前8位

                    if (aPrefix < bPrefix) {
                        return -1;
                    } else if (aPrefix > bPrefix) {
                        return 1;
                    } else {
                        return 0;
                    }
                    });
                
                const cusTrainInfoBox=document.getElementById('cusTrainInfo');
                const cusClsByInsTitle=document.createElement('div');
                cusClsByInsTitle.innerHTML=`■ 教练的会员上课概况`;
                cusClsByInsTitle.style.fontSize='16px';
                cusClsByInsTitle.style.color='#3b6ba1';
                cusClsByInsTitle.style.fontWeight='bold';
                cusClsByInsTitle.style.marginLeft='0px';
                cusTrainInfoBox.appendChild(cusClsByInsTitle);
                sortInsList.forEach(ins=>{
                    showCusClsByIns(ins);
                });

                const chartBox = document.getElementById('insClsInfo');
                chartBox.innerHTML = '';
                insList.forEach(ins => {                
                    showInsClsStatByIns(ins, insClsRecs, chartBox);
                });
            })
            .catch(error => console.error('Error:', error));
        });

        function showCusClsRank0(){
            const dateInput = new Date();
            const today = dateToString(dateInput, 'date');
            const interval=document.getElementById('interval0').value;
            fetch('./get_all_cls_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 'dateInput': today,'interval':interval })
            })
            .then(response=>response.json())
            .then(data=>{
                const chartBox = document.getElementById('cusClsRank');
                if(data['res']==='ok'){
                    console.log('rank data 0:',data)
                    showCusClsRank(data['data']);                    
                }else{
                    chartBox.innerHTML = '';
                }
                
            })
            .catch(error=>console.error('Error:',error));
            const cusClsRank=document.getElementById('cusClsRank');

        }

        function showCusClsRank(data){
            const cusClsRank=document.getElementById('cusClsRank');
            cusClsRank.innerHTML='';
            const rankData=data['all_cls'];
            const chartContainer = document.createElement('div');
            // chartContainer.classList.add('chart-wrapper');
            chartContainer.style.width='380px';
            chartContainer.style.height='200px';
            cusClsRank.appendChild(chartContainer);

            // 初始化图表
            const chart = echarts.init(chartContainer);

            // 定义横坐标数据
            // const xAxisData = ['6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'];
            const xAxisData=rankData.map(value=>value[1]);
            // 定义总数数据
            // let totalData = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 11, 10, 9, 8, 7, 6, 5, 4];
            const YAxisData=rankData.map(value=>value[2]);

            const showDataZoom = xAxisData.length > 10;
            const startValue = 0;
            // showDataZoom ? Math.max(0, xAxisData.length - 10) / xAxisData.length * 100 : 0;
            const endValue = 10/xAxisData.length*100;


            // 配置图表选项
            const titleStr=`◆ 会员上课统计排名`;
            const options = {
                // title: {
                //     text: titleStr,
                //     textStyle: {
                //         color: '#a479b8', // 标题颜色
                //         fontSize: 14 // 标题字体大小
                //     }
                // },
                tooltip:{
                    trigger:'axis'
                },
                xAxis: {
                    type: 'category',
                    name:'会员',
                    data: xAxisData,
                    axisLabel: {
                        //color: '#bd8333', // 坐标轴文字颜色
                        fontSize: 10, // 坐标轴文字大小
                        rotate:80
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '上课节数',
                        position: 'left',
                        axisLabel: {
                            //color: 'blue', // 坐标轴文字颜色
                            fontSize: 10 // 坐标轴文字大小
                        }
                    }
                ],
                series: [
                    {
                        name: '上课节数',
                        type: 'bar',
                        yAxisIndex: 0,
                        data: YAxisData,
                        itemStyle: {
                            color: '#a479b8' // 设置柱状图的颜色
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: function (params) {
                                return params.value === 0 ? '' : params.value;
                            }
                        }
                    }
                ],
                dataZoom: showDataZoom ? [
                {
                    type: 'slider',
                    start: startValue,
                    end: endValue,
                    handleSize: '150%',   // 增大 handleSize 以便触摸
                    height: 20,           // 调整高度以适应移动设备
                    handleStyle: {
                        color: '#a7b7cc' // 调整 handle 的颜色以便更好地查看
                    },
                    bottom:10
                },
                {
                    type: 'inside',       // 添加 inside 类型 dataZoom 以便触摸缩放
                    start: startValue,
                    end: endValue
                }]:[]
            };

            // 使用配置项生成图表
            chart.setOption(options);


        }


        function showInsClsChart2(){
            const dateInput = new Date();
            const today = dateToString(dateInput, 'date');
            const interval=document.getElementById('interval').value;
            fetch('./get_ins_cls_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 'dateInput': today,'interval':interval })
            })
            .then(response=>response.json())
            .then(data=>{
                const chartBox = document.getElementById('insClsInfo');
                if(data['res']==='ok'){
                    const insClsRecs = data['data'];
                    chartBox.innerHTML = '';
                    insList.forEach(ins => {                
                        showInsClsStatByIns(ins, insClsRecs, chartBox);
                    });
                }else{
                    chartBox.innerHTML = '';
                }
                
            })
            .catch(error=>console.error('Error:',error));
        }

        function showCusClsByIns(ins){
            const insId=ins.slice(0,8)
            fetch('./get_latest_cus_train_days',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body:JSON.stringify({'insId':insId})
            })
            .then(response=>response.json())
            .then(data=>{
                if(data['res']==='ok'){
                    // console.log(data)                    
                    showCusInfo(data['data'],data['ins_name'][0]);                    
                }
                

            })
            .catch(error=>console.error('Error:',error));           

           
        }


        function showCusInfo(data,insName){
            const cusTrainInfoBox=document.getElementById('cusTrainInfo');
            // cusTrainInfoBox.innerHTML='';
            


            const divInsTitle=document.createElement('div');
            divInsTitle.innerHTML=`<span style='color:#7c899c;font-size:13px;'>—  ${insName}教练</span>`;
            divInsTitle.style.marginTop='20px';
            // divInsTitle.style.color='#5574a3';
            divInsTitle.style.fontWeight='bold';
            const hrDiv=document.createElement('div');
            hrDiv.style.display='flex';
            hrDiv.style.flexDirection='row';
            hrDiv.style.justifyContent='start';
            const hr=document.createElement('hr');
            hr.style.width='90px';
            hrDiv.appendChild(hr);
            cusTrainInfoBox.appendChild(divInsTitle);
            cusTrainInfoBox.appendChild(hrDiv);


            let cusNotStartStr='';
            let cusIn7DaysStr='';
            let cusIn7to30DaysStr='';
            let cusOver30DaysStr='';

            let notStartCount=0;
            let in7DaysCount=0;
            let in7To30DaysCount=0;
            let over30DaysCount=0;

            data.forEach(item => {
                if(item[3]==='-'){                    
                    cusNotStartStr=cusNotStartStr+item[1]+',';
                    notStartCount+=1;
                }else{
                    if(parseFloat(item[3])<=7){
                        cusIn7DaysStr+=item[1]+',';
                        in7DaysCount+=1;
                    }else if(parseFloat(item[3])<=30){
                        cusIn7to30DaysStr+=item[1]+',';
                        in7To30DaysCount+=1;
                    }else{
                        cusOver30DaysStr+=item[1]+',';
                        over30DaysCount+=1;
                    }

                }
            });            

            const totalCusCount=notStartCount+in7DaysCount+in7To30DaysCount+over30DaysCount;



            cusNotStartStr=cusNotStartStr.slice(0,-1);
            cusIn7DaysStr=cusIn7DaysStr.slice(0,-1);
            cusIn7to30DaysStr=cusIn7to30DaysStr.slice(0,-1);
            cusOver30DaysStr=cusOver30DaysStr.slice(0,-1);

            // console.log(cusNotStartStr,cusIn7DaysStr,cusIn7to30DaysStr,cusOver30DaysStr);

            if(cusNotStartStr){
                const divBox=document.createElement('div');
                divBox.classList.add('index-small-div');
                const divTitleBox=document.createElement('div');
                divTitleBox.classList.add('show-ins-cls_stat-cus-title');

                const divTitle=document.createElement('div');
                divTitle.style.backgroundColor='#3ab559';
                divTitle.textContent='还没开始上课的会员';
                divTitle.classList.add('index-small-title');

                const divCount=document.createElement('div');
                divCount.innerHTML=`${notStartCount}人`;
                divCount.classList.add('show-ins-cls-stat-count-box');
                divCount.style.color='#3ab559';

                divTitleBox.appendChild(divTitle);
                divTitleBox.appendChild(divCount);


                const divContent=document.createElement('div');
                divContent.textContent=cusNotStartStr;
                divContent.classList.add('index-small-content');
                divBox.appendChild(divTitleBox);
                divBox.appendChild(divContent);
                cusTrainInfoBox.appendChild(divBox);
            }

            if(cusIn7DaysStr){               
                const divBox=document.createElement('div');
                divBox.classList.add('index-small-div');                
                const divTitleBox=document.createElement('div');
                divTitleBox.classList.add('show-ins-cls_stat-cus-title');
                
                const divTitle=document.createElement('div');
                divTitle.style.backgroundColor='#2b62ed';
                divTitle.textContent='最近7天在训练的会员';
                divTitle.classList.add('index-small-title');

                const divCount=document.createElement('div');
                divCount.innerHTML=`${in7DaysCount}人`;
                divCount.classList.add('show-ins-cls-stat-count-box');
                divCount.style.color='#2b62ed';

                divTitleBox.appendChild(divTitle);
                divTitleBox.appendChild(divCount);

                const divContent=document.createElement('div');
                divContent.textContent=cusIn7DaysStr;
                divContent.classList.add('index-small-content');
                divBox.appendChild(divTitleBox);
                divBox.appendChild(divContent);
                cusTrainInfoBox.appendChild(divBox);
            }

            if(cusIn7to30DaysStr){
                
                const divBox=document.createElement('div');
                divBox.classList.add('index-small-div');                
                const divTitleBox=document.createElement('div');
                divTitleBox.classList.add('show-ins-cls_stat-cus-title');
                
                const divTitle=document.createElement('div');
                divTitle.style.backgroundColor='#2f53ad';
                divTitle.textContent='7-30天内在训练的会员';
                divTitle.classList.add('index-small-title');

                const divCount=document.createElement('div');
                divCount.innerHTML=`${in7To30DaysCount}人`;
                divCount.classList.add('show-ins-cls-stat-count-box');
                divCount.style.color='#2f53ad';

                divTitleBox.appendChild(divTitle);
                divTitleBox.appendChild(divCount);

                const divContent=document.createElement('div');
                divContent.textContent=cusIn7to30DaysStr;
                divContent.classList.add('index-small-content');
                divBox.appendChild(divTitleBox);
                divBox.appendChild(divContent);
                cusTrainInfoBox.appendChild(divBox);
            }

            if(cusOver30DaysStr){   
                const divBox=document.createElement('div');
                divBox.classList.add('index-small-div');                
                const divTitleBox=document.createElement('div');
                divTitleBox.classList.add('show-ins-cls_stat-cus-title');
                
                const divTitle=document.createElement('div');
                divTitle.style.backgroundColor='#f55b49';
                divTitle.textContent='超过30天没有训练的会员';
                divTitle.classList.add('index-small-title');

                const divCount=document.createElement('div');
                divCount.innerHTML=`${over30DaysCount}人`;
                divCount.classList.add('show-ins-cls-stat-count-box');
                divCount.style.color='#f55b49';

                divTitleBox.appendChild(divTitle);
                divTitleBox.appendChild(divCount);

                const divContent=document.createElement('div');
                divContent.textContent=cusOver30DaysStr;
                divContent.classList.add('index-small-content');
                divBox.appendChild(divTitleBox);
                divBox.appendChild(divContent);
                cusTrainInfoBox.appendChild(divBox);
            }

            cusTrainInfoBox.classList.add('index-cus-train-box');
            divInsTitle.innerHTML=`<span style='color:#7c899c;font-size:13px;'>—  ${insName}教练</span>&nbsp;&nbsp;&nbsp; <span style='font-size:12px;'>共有会员 ${totalCusCount} 人</span>`;
            
            


        }

        function showInsClsStatByIns(ins,insClsRecs,chartBox){
            const prds={
                '6':0,
                '7':0,
                '8':0,
                '9':0,
                '10':0,
                '11':0,
                '12':0,
                '12':0,
                '14':0,
                '15':0,
                '16':0,
                '17':0,
                '18':0,
                '19':0,
                '20':0,
                '21':0,
                '22':0,
                '23':0                
            };

            const insId=ins.slice(0,8);
            const insName=ins.slice(8,);          

            if(insClsRecs){
                insClsRecs.forEach(rec=>{                         
                    if(rec[0]===insId){
                        prds[rec[2].toString()]=rec[3];
                    }                        
                });
                const qtySum = Object.values(prds).reduce((acc, cur) => acc + cur, 0);
                if(qtySum>0){
                    const chart=showInsClsChart(prds,insName);                    
                    chartBox.appendChild(chart);
                }

            }else{
                chartBox.innerHTML='';
            }
        
        }


        function showInsClsChart(prds,insName){
            const chartContainer = document.createElement('div');
            chartContainer.id=insName;
            // chartContainer.classList.add('chart-wrapper');
            chartContainer.style.width='380px';
            chartContainer.style.height='200px';
            

            // 初始化图表
            const chart = echarts.init(chartContainer);

            // 定义横坐标数据
            // const xAxisData = ['6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'];
            const xAxisData=Object.keys(prds);
            // 定义总数数据
            // let totalData = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 11, 10, 9, 8, 7, 6, 5, 4];
            const totalData=Object.values(prds);
            const sum = totalData.reduce((accumulator, currentValue) => {
                return accumulator + currentValue;
            }, 0);

            // 配置图表选项
            const titleStr=`— ${insName}教练 （上课共${sum}节）`;
            const options = {
                title: {
                    text: titleStr,
                    textStyle: {
                        color: '#bd8333', // 标题颜色
                        fontSize: 14 // 标题字体大小
                    }
                },
                xAxis: {
                    type: 'category',
                    name:'时段',
                    data: xAxisData,
                    axisLabel: {
                        //color: '#bd8333', // 坐标轴文字颜色
                        fontSize: 10 // 坐标轴文字大小
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '上课节数',
                        position: 'left',
                        axisLabel: {
                            //color: 'blue', // 坐标轴文字颜色
                            fontSize: 10 // 坐标轴文字大小
                        }
                    }
                ],
                series: [
                    {
                        name: '上课节数',
                        type: 'bar',
                        yAxisIndex: 0,
                        data: totalData,
                        itemStyle: {
                            color: '#bd8333' // 设置柱状图的颜色
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: function (params) {
                                return params.value === 0 ? '' : params.value;
                            }
                        }
                    }
                ]
            };

            // 使用配置项生成图表
            chart.setOption(options);

            return chartContainer;
            
        }

    </script>
  
</body>
</html>
